package edu.ptu.springboot04.filer;

import edu.ptu.springboot04.utils.JWTUtil;
import edu.ptu.springboot04.utils.LoginUser;
import edu.ptu.springboot04.utils.RedisUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @BelongsProject: springboot04
 * @BelongsPackage: edu.ptu.springboot04.filer
 * @Author: HYJ
 * @CreateTime: 2025-03-27  20:36
 * @Description: JWT认证过滤器 - 处理请求头中的Token验证
 * 1. 从请求头获取Token
 * 2. 验证Token有效性
 * 3. 从Redis获取用户信息
 * 4. 设置SecurityContext认证信息
 * @Version: 1.0
 */
@Component
public class AuthJwtUtilFilter extends OncePerRequestFilter {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 过滤器核心逻辑
     *
     * @param request     HTTP请求对象
     * @param response    HTTP响应对象
     * @param filterChain 过滤器链
     * @throws ServletException 服务端异常
     * @throws IOException      IO异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 从请求头获取Token
        String token = request.getHeader("token");

        // 无Token直接放行（后续过滤器会处理认证）
        if (token == null) {
            filterChain.doFilter(request, response);
        }

        // 验证Token有效性
        boolean b = JWTUtil.vetifyToken(token);
        if (!b) {
            throw new RuntimeException("token 验证失败");
        }

        // 解析用户ID并查询Redis
        Long userId = JWTUtil.getUserId(request);
        LoginUser user = redisUtil.getCacheObject("user:" + userId);

        if (Objects.isNull(user)) {
            throw new RuntimeException("token 验证失败");
        }

        // 创建认证令牌并设置到安全上下文
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request, response);
    }
}
